//
//  kslajiViewController.m
//  tongxiangOASystem
//
//  Created by michael on 2018/4/19.
//  Copyright © 2018年 czd. All rights reserved.
//

#import "kslajiViewController.h"
#import "fajianTableViewCell.h"

#import "fajianViewController.h"
#import "OASendMessageViewController.h"
#import "OASendMessageDetailController.h"
#import "daibanTableViewCell.h"
#import "shoujianViewController.h"
#import "LGLSearchBar.h"
@interface kslajiViewController ()

@end

@implementation kslajiViewController

- (void)viewDidLoad {
    [super viewDidLoad];
        _muarray = [NSMutableArray array];
        self.view.backgroundColor = [UIColor colorWithHexString:@"efeff4"];
        UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(10, 10, 80, 40)];
        button.backgroundColor = [UIColor colorWithHexString:@"5ca9f7"];
        [button setTitle:@"删除" forState:UIControlStateNormal];
            [button addTarget:self action:@selector(piliangaction) forControlEvents:UIControlEventTouchUpInside];

        [self.view addSubview:button];
 LGLSearchBar * searchBar = [[LGLSearchBar alloc] initWithFrame:CGRectMake(button.right, 10, KScreenWidth-button.width-10, 40) searchBarStyle:LGLSearchBarStyleDefault];
[searchBar setSearchBarBordeWidth:0.1 bordColor:[UIColor clearColor] bordRadius:0];
//[searchBar setSearchBarImage:@"search" scale:30];
        [searchBar searchBarTextSearchTextBlock:^(NSString *searchText) {
        NSLog(@"%@", searchText);
        if (searchText.length>0) {
        _isSearching = @"yes";
    _searchstr = searchText;
//        [self loadSearchData];
    [_tableView headerBeginRefreshing];

}
     else{
[self.view makeToast:@"搜索关键字不能为空"];
}

    }];
    [self.view addSubview:searchBar];
 _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 50+5, KScreenWidth,self.view.height-kTopHeight-55-44-LL_TabbarSafeBottomMargin) style:UITableViewStylePlain];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.tableView.backgroundColor = [UIColor colorWithHexString:@"efeff4"];
//        self.tableView.backgroundColor = [UIColor yellowColor];

_tableView.dataSource = self;
_tableView.delegate = self;
[self.view addSubview:_tableView];
   self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
 __weak typeof(self) weakSelf = self;

    [self.tableView addHeaderWithCallback:^{

if([self.tableView isHeaderRefreshing])
{


}else{
        weakSelf.currentPage = 1;
         if ([weakSelf.isSearching isEqualToString:@"yes"]) {
     [weakSelf loadSearchData];
}else{
NSLog(@"1111");
        [weakSelf loadData]; //加载网络数据

}
}
    }];
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    [self.tableView headerBeginRefreshing];
    
    [self.tableView addFooterWithCallback:^{
        if ((self.currentPage - 1)*KPageSize < self.totalCounts ){
        if ([weakSelf.isSearching isEqualToString:@"yes"]) {
     [weakSelf loadSearchMore];
}
     else {
     [weakSelf loadMore];
     }
        }else{
            
            [weakSelf.tableView footerEndRefreshing];
            [self.view makeToast:@"没有更多了"];
            
        }
        
    }];
    
    // Do any additional setup after loading the view.
}

- (void)loadSearchData{
    __weak typeof(self) weakSelf = self;
_currentPage = 1;
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"condition":_searchstr},@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
     [HttpTools requestWithURL:KexchkssearchURL arrays:array method:@"trasmailSearch" success:^(id JSON) {
    NSLog(@"%@",JSON);

      if (self.currentPage ==1) {
            [self.dataArray removeAllObjects];
        }
      _dataArray =   [NSMutableArray array];
        NSArray *array = JSON[@"data"];
                self.totalCounts =[JSON[@"number"] intValue];
if(JSON[@"number"]){
_titlename = [NSString stringWithFormat:@"垃圾箱(%@)",JSON[@"number"] ];
   if (self.selectRowBlock) {
  self.selectRowBlock(_titlename);
  }
}else{
_titlename  = @"垃圾箱";
  if (self.selectRowBlock) {
  self.selectRowBlock(_titlename);
  }
}
         for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
_adic= JSON[@"display"];

        [weakSelf.tableView footerEndRefreshing];
        [weakSelf.tableView reloadData];
        weakSelf.currentPage++;
        
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
        
    } failure:^(NSError *error) {
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
    }];

}
- (void)loadSearchMore{
    __weak typeof(self) weakSelf = self;

NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"condition":_searchstr},@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
 [HttpTools requestWithURL:KexchkssearchURL arrays:array method:@"trasmailSearch" success:^(id JSON) {

       NSArray *array = JSON[@"data"];

 for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
_adic= JSON[@"display"];

   self.totalCounts =[JSON[@"number"] intValue];


        [weakSelf.tableView footerEndRefreshing];
        [weakSelf.tableView reloadData];
        weakSelf.currentPage++;

        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
     
    } failure:^(NSError *error) {

        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
    }];
}
- (void)viewWillAppear:(BOOL)animated{

// if (self.selectRowBlock) {
//  self.selectRowBlock(_titlename);
//  }
    [self.tableView headerBeginRefreshing];
_isSearching = @"no";
}
-(NSMutableArray*)dataArray{
    if (_dataArray == nil) {
        _dataArray =   [NSMutableArray array];
    }
    return _dataArray;
}
- (void)loadData{
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
       [self.muarray removeAllObjects];

self.currentPage = 1;
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    [HttpTools requestWithURL:KexchksmailURL arrays:array method:@"dustbinPage" success:^(id JSON) {
          [MBProgressHUD hideAllHUDsForView:self.view animated:YES];

    NSLog(@"%@",JSON);
        if (self.currentPage ==1) {
            [self.dataArray removeAllObjects];
        }
      _dataArray =   [NSMutableArray array];
        NSArray *array = JSON[@"data"];
        self.totalCounts =[JSON[@"number"] intValue];

if(JSON[@"number"]){
_titlename = [NSString stringWithFormat:@"垃圾箱(%@)",JSON[@"number"] ];
   if (self.selectRowBlock) {
  self.selectRowBlock(_titlename);
  }
}else{
_titlename  = @"垃圾箱";
  if (self.selectRowBlock) {
  self.selectRowBlock(_titlename);
  }
}
         for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
_adic= JSON[@"display"];

        [self.tableView reloadData];
        [self.tableView headerEndRefreshing];
        self.currentPage++;
        if (self.dataArray.count ==0) {
            [self.view makeToast:@"暂时还没数据哦"];
        }
    } failure:^(NSError *error) {
          [MBProgressHUD hideAllHUDsForView:self.view animated:YES];

        [self.tableView headerEndRefreshing];
        
    }];
    
}
- (void)loadMore{
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    [HttpTools requestWithURL:KexchksmailURL arrays:array method:@"draftsPage" success:^(id JSON) {
    
            NSArray *array = JSON[@"data"];

 for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
//_adic= JSON[@"display"];

self.currentPage++;
        [self.tableView footerEndRefreshing];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [self.tableView footerEndRefreshing];
    }];
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

     NSDictionary *dic = self.dataArray[indexPath.row];

    CGFloat  titleFloat  = [OAToolBox sizebyText:dic[@"subject"] font:14 minsWidth:70];

    return  titleFloat+10+10+20;


}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

 static NSString *CellIdentifier = @"Cell";

    fajianTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
  if (cell==nil) {
        cell=[[fajianTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
 NSDictionary *dic = self.dataArray[indexPath.row];
    cell.dic = dic;
    cell.adic = _adic;
    cell.number = [NSString stringWithFormat:@"%ld",(long)indexPath.row+1];
     cell.button.tag = indexPath.row;
    [cell.button addTarget:self action:@selector(selaction:) forControlEvents:UIControlEventTouchUpInside];
    return cell;


 }
 - (void)selaction:(UIButton *)btn{
 btn.selected = !btn.selected;
 if (btn.selected) {
     NSDictionary *dic = _dataArray[btn.tag];
 [_muarray addObject:dic[@"unid"]];
}else{
     NSDictionary *dic = _dataArray[btn.tag];

[_muarray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    if ([obj isEqualToString:dic[@"unid"]]) {
        [_muarray removeObject:obj];
    }
}];

}

// [_tableView reloadData];
 
 }
 - (void)piliangaction{
if (_muarray.count>0) {
    

if (_muarray.count>10) {
            [self.view makeToast:@"删除不能超过10条"];

}else{
                 __weak typeof(self) weakSelf = self;

NSString *string = [_muarray componentsJoinedByString:@"."];
  NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
   NSArray * array = @[@{@"view":@"4"},@{@"sName":userId},@{@"userId":string}];
    [HttpTools requestWithURL:@"exchdelete" arrays:array method:@"mailksdelete" success:^(id JSON) {
    if ([[NSString stringWithFormat:@"%@",JSON]isEqualToString:@"20"]) {
       [self.view.window makeToast:@"删除成功"];
       [weakSelf.muarray removeAllObjects];
                [self loadData];
}else{
                [self.view.window makeToast:@"删除失败"];
//                       [weakSelf.muarray removeAllObjects];

}


    } failure:^(NSError *error) {
                [self.view.window makeToast:@"删除失败"];
//                       [weakSelf.muarray removeAllObjects];


    }];

}
}else{
                [self.view.window makeToast:@"请选择删除邮件"];

}
}
 -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
            NSDictionary *dic = self.dataArray[indexPath.row];
      UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

    OASendMessageDetailController * detailVC = [storyBoard instantiateViewControllerWithIdentifier:@"NewSendDetailVCID"];
    detailVC.fileId = dic[@"unid"];
    detailVC.type = @"ks";
                                   detailVC.hidesBottomBarWhenPushed = YES;

    [self.navigationController pushViewController:detailVC animated:YES];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end



